using System;
using System.IO;

using Atomic.Structures;

namespace Atomic.Vasp
{
	/// <summary>
	/// Provides an object mapping to the VASP pseudopotentials.
	/// </summary>
	[Serializable]
	public class VaspPotentials
	{
		/// <summary>
		/// Creates a new instance mapping to the directory specified in the VASP_PP_PATH environment variable.
		/// </summary>
		public VaspPotentials()
			: this(new DirectoryInfo(Environment.GetEnvironmentVariable("VASP_PP_PATH") ?? Path.Combine(AtomicEnvironment.HomeDirectory.FullName, "local/vasp/pot_GGA")))
		{
			// VASP_PP_PATH is also the name used in ASE's VASP module.
		}

		public VaspPotentials(DirectoryInfo potentialsDirectory)
		{
			if (!Directory.Exists(potentialsDirectory.FullName))
			{
				throw new ArgumentException("Directory specified for pseudopotentials doesn't exist.");
			}

			PotentialsDirectory = potentialsDirectory;
		}

		public string Read(Atom atom)
		{
			if (atom is SpinPolarizedAtom)
			{
				atom = ((SpinPolarizedAtom)atom).BaseAtom;
			}

			string s;
			using (StreamReader reader = new StreamReader(Path.Combine(PotentialsDirectory.FullName, atom.Symbol, "POTCAR")))
			{
				// Not extremely large files.
				s = reader.ReadToEnd();
				reader.Close();
			}

			return s;
		}

		public DirectoryInfo PotentialsDirectory
		{
			get;
			private set;
		}
	}
}
